<template>
  <div class="container">
    <div class="header" @click="$router.back(-1)">
      <i class="el-icon-arrow-left c-font-b"></i>
      <span>{{ foodId ? "菜谱编辑" : "菜谱新增" }}</span>
    </div>
    <!--    表单区域-->
    <div class="form">
      <el-form
        ref="editFormRef"
        :rules="editFormRules"
        :model="editForm"
        label-width="80px"
        label-position="right"
      >
        <el-form-item label="食堂" prop="region">
          <el-select
            @change="selectCanteen"
            v-model="editForm.region"
            placeholder="请选择食堂"
            style="width: 300px"
            size="small"
          >
            <el-option
              v-for="item in canteenData"
              :label="item.name"
              :value="item.id"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期" prop="businessTime">
          <el-date-picker
            style="width: 300px"
            size="small"
            v-model="editForm.businessTime"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            type="textarea"
            v-model="editForm.description"
            size="small"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="图片">
          <el-upload
            action="/api/storages"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :file-list="fileList"
            :before-upload="checkFileType"
            :headers="header"
            :on-exceed="handleOnExceed"
            :limit="1"
            name="multipartFile"
          >
            <el-icon><plus /></el-icon>
          </el-upload>
          <el-dialog v-model="imgDialogVisible">
            <img :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item> -->
        <el-form-item
          label="套餐档口"
          label-width="100px"
          style="border-bottom: 1px solid #edeff3; padding-bottom: 10px"
        >
          <el-button type="primary" size="small" @click="addBasicFood"
            >添加</el-button
          >
          <div class="tags">
            <el-tag
              style="margin-right: 5px"
              v-for="tag in basicFoods"
              :key="tag.id"
            >
              {{ tag.foodName }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item
          label="碗碗菜档口"
          label-width="100px"
          style="border-bottom: 1px solid #edeff3; padding-bottom: 10px"
        >
          <el-button type="primary" size="small" @click="addWwc"
            >添加</el-button
          >
          <div class="tags">
            <el-tag style="margin: 5px" v-for="tag in bolwsData" :key="tag.id">
              {{ tag.foodName + tag.price + "元" }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item
          label-width="100px"
          label="自选称菜档口"
          style="border-bottom: 1px solid #edeff3; padding-bottom: 10px"
        >
          <el-button type="primary" size="small" @click="addChooseFood"
            >添加</el-button
          >
          <div class="tags">
            <el-tag
              style="margin-right: 5px"
              v-for="tag in optionalFoods"
              :key="tag.id"
            >
              {{ tag.foodName }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item>
          <TsButton
            v-show="foodId"
            label="提交"
            perms="food-menu:submit:put"
            type="success"
            size="small"
            @click="submitAudit"
          ></TsButton>
          <el-button type="primary" size="small" @click="submitFood"
            >保存</el-button
          >
          <el-button size="small" @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--    添加基础套餐对话框-->
    <el-dialog v-model="dialogVisible" title="选择基础套餐" width="30%">
      <div class="dialog-header">
        <el-input
          style="width: 140px; margin-right: 5px"
          v-model="searchForm.name"
          placeholder="请输入商品名称"
          size="small"
        ></el-input>
        <el-button
          type="primary"
          size="small"
          icon="el-icon-search"
          @click="searchFood"
          >搜索</el-button
        >
        <el-button size="small" icon="el-icon-refresh" @click="reset"
          >重置</el-button
        >
      </div>
      <div class="dialog-content">
        <!--        多选框-->
        <el-checkbox-group v-model="basicForm" style="padding: 10px">
          <el-checkbox
            v-for="item in checkedBasicBoxs"
            :key="item.id"
            :checked="item.checked"
            :label="item"
            name="type"
            >{{ item.name }}</el-checkbox
          >
        </el-checkbox-group>
      </div>
      <!--      标签Tags-->
      <div class="tags">
        <el-form-item>
          <el-tag
            size="small"
            v-for="tag in basicForm"
            :key="tag.id"
            style="margin: 5px"
          >
            {{ tag.name }}
          </el-tag>
        </el-form-item>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitBasicFood">确定</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <!--    碗碗菜对话框-->
    <el-dialog v-model="wwcDialogVisible" title="选择碗碗菜" width="50%">
      <div class="dialog-header">
        <span class="c-m-r-5">商品名称</span>
        <el-input
          v-model="searchForm.name"
          style="width: 200px; margin-right: 5px"
          placeholder="请输入商品名称"
          size="small"
        ></el-input>
        <el-button
          type="primary"
          size="small"
          icon="el-icon-search"
          @click="searchFood"
          >搜索</el-button
        >
        <el-button size="small" icon="el-icon-refresh" @click="reset"
          >重置</el-button
        >
      </div>
      <div class="dialog-content" style="padding: 20px">
        <div class="item" v-for="(item, index) in wwcFoodData" :key="index">
          <div class="item-left">
            <el-form inline label-position="left">
              <el-form-item :label="item.name" label-width="120px">
                <el-radio-group v-model="wwcForm[index]">
                  <el-radio
                    v-for="wwcItem in wwcprice"
                    :label="wwcItem.price"
                    :key="wwcItem.price"
                    @change="chengeRadio($event, item.id)"
                    name="type"
                    >{{ wwcItem.price + "元" }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-form>
          </div>
          <div class="item-right">
            <el-button
              type="primary"
              size="small"
              @click="addWwcFood(index, item)"
              >添加</el-button
            >
          </div>
        </div>
      </div>
      <!--      标签Tags-->
      <div class="tags">
        <el-tag
          size="small"
          v-for="tag in bowls"
          :key="tag.price"
          :label="tag.price"
          closable
          @close="removeFood(tag.id)"
          style="margin-right: 10px"
        >
          {{ tag.name + tag.price + "元" }}
        </el-tag>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitWwcFood">确定</el-button>
          <el-button @click="cancelBolws">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <!--    添加自选套餐对话框-->
    <el-dialog v-model="chooseDialogVisible" title="选择自选称菜" width="30%">
      <div class="dialog-header">
        <el-input
          v-model="searchForm.name"
          style="width: 140px; margin-right: 5px"
          placeholder="请输入商品名称"
          size="small"
        ></el-input>
        <el-button
          type="primary"
          size="small"
          icon="el-icon-search"
          @click="searchFood"
          >搜索</el-button
        >
        <el-button size="small" icon="el-icon-refresh" @click="reset"
          >重置</el-button
        >
      </div>
      <div class="dialog-content">
        <!--        多选框-->
        <el-checkbox-group v-model="chooseForm" style="padding: 10px">
          <el-checkbox
            v-for="item in checkedChooseBoxs"
            :key="item.id"
            :checked="item.checked"
            :label="item"
            >{{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <!--      标签Tags-->
      <div class="tags">
        <el-form-item>
          <el-tag
            size="small"
            v-for="tag in chooseForm"
            :key="tag.id"
            style="margin: 5px"
          >
            {{ tag.name }}
          </el-tag>
        </el-form-item>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitChooseFood">确定</el-button>
          <el-button @click="chooseDialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { onMounted, reactive, ref } from "vue";
import {
  addFoodMenu,
  getBlowsPrice,
  getCanteenFoodList,
  getCanteenList,
  getFoodMenuList,
  queryFood,
  updateFoodMenu,
  menuAudit,
} from "../../../api/canteen/menu-managerApi";
// import { Plus } from "@element-plus/icons";
import { ElMessage } from "element-plus";
import Cookies from "js-cookie";
import router from "../../../router";
import { useRoute } from "vue-router";
export default {
  // components: {
  //   Plus,
  // },
  name: "MenuEdit",
  setup() {
    function checkFileType(file) {
      const fileName = file.name;
      const fileType = fileName.substring(fileName.lastIndexOf("."));
      // jpeg,.png,.jpg,.bmp,.gif
      if (
        fileType === ".jpg" ||
        fileType === ".png" ||
        fileType === ".jpeg" ||
        fileType === ".bmp" ||
        fileType === ".gif"
      ) {
        // 不处理
      } else {
        ElMessage.error("请上传正确的图片类型,jpeg,.png,.jpg,.bmp,.gif文件,");
        return false;
      }
    }
    function handleOnExceed() {
      ElMessage.warning("只能上传一张图片，请删除图片后重试");
    }
    const fileList = ref([]);
    //返回
    function cancel() {
      router.back(-1);
    }
    //表单数据
    const editForm = reactive({});
    //食堂数据
    const canteenData = ref([]);
    //获取食堂数据
    function getCanteen() {
      getCanteenList().then((res) => {
        canteenData.value = res.data;
      });
    }
    const header = reactive({ Authorization: Cookies.get("token") });
    //上传图片预览
    function handlePictureCardPreview(file) {
      console.log(file);
    }
    //移除上传图片钩子函数
    function handleRemove(file, fileList) {
      fileList.value = fileList;
    }
    //图片上传成功时的回调
    function handleSuccess(file) {
      editForm.images = file.data.url;
    }
    const imgDialogVisible = ref(false);
    const dialogImageUrl = ref("");
    //对话框显示与隐藏
    const dialogVisible = ref(false);
    //添加基础菜单
    function addBasicFood() {
      basicForm.value = [];
      if (canteenId.value) {
        checkedBasicBoxs.value = null;
        getCanteenFoodList(canteenId.value).then((res) => {
          checkedBasicBoxs.value = res.data.content;
          //数组增加checked属性，控制选中和未选中
          for (const id of checkedBasicBoxs.value) {
            basicFoods.value.map((item) => {
              if (item.foodId === id.id) {
                id.checked = true;
              }
            });
          }
          dialogVisible.value = true;
        });
      } else {
        ElMessage({
          message: "请先选择食堂后，再操作",
          type: "warning",
        });
      }
    }
    //食堂ID
    const canteenId = ref("");
    const basicForm = ref([]);
    //多选框数据
    const checkedBasicBoxs = ref([]);
    //通过食堂Id获取菜品信息
    function selectCanteen(val) {
      canteenId.value = val;
      bowls.value = [];
      optionalFoods.value = [];
      basicFoods.value = [];
    }
    const checkedTags = ref([]);
    //基础套餐组装数组
    const basicFoods = ref([]);
    //基础套餐提交
    function submitBasicFood() {
      basicFoods.value = [];
      basicForm.value.map((item) => {
        basicFoods.value.push({
          foodId: item.id,
          foodName: item.name,
          foodType: item.type,
          type: 1,
        });
      });
      let set = new Set(basicFoods.value);
      basicFoods.value = Array.from(set);
      dialogVisible.value = false;
    }
    //碗碗菜数据
    const wwcForm = ref([]);
    const bolwsData = ref([]);
    //碗碗菜对话框显示与隐藏
    const wwcDialogVisible = ref(false);
    const wwcFoodData = ref([]);
    //碗碗菜价格
    const wwcprice = ref([]);
    let foodMap = new Map();
    //添加碗碗菜
    function addWwc() {
      if (!canteenId.value) {
        ElMessage({
          message: "请选择食堂后，再操作",
          type: "warning",
        });
      } else {
        wwcForm.value = [];
        bowls.value = [];
        wwcDialogVisible.value = true;
        getCanteenFoodList(canteenId.value).then((res) => {
          wwcFoodData.value = res.data.content;
          wwcFoodData.value.map((item, index) => {
            foodMap.set(item.id, index);
          });
          bolwsData.value.map((item) => {
            wwcForm.value[foodMap.get(item.foodId)] = item.price;
            bowls.value.push({
              name: item.foodName,
              id: item.foodId,
              price: item.price,
            });
          });
        });
      }
    }

    //碗碗菜tags
    const wwcTags = ref([]);
    //碗碗菜重装数组
    const bowls = ref([]);
    function addWwcFood(index, val) {
      let bolwMap = new Map();
      //获取价格
      if (wwcMap.has(wwcFoodData.value[index].id)) {
        val.price = wwcMap.get(wwcFoodData.value[index].id);
        bowls.value.forEach((item, index) => {
          bolwMap.set(item.id, index);
        });
        if (bolwMap.has(val.id)) {
          //  存在修改值
          bowls.value[bolwMap.get(val.id)] = val;
        } else {
          bowls.value.push(val);
        }
      }
    }
    //提交碗碗菜
    function submitWwcFood() {
      // if (bowls.value.length == 0) {
      //   ElMessage.warning("请选择菜品");
      // } else {
      bolwsData.value = [];
      bowls.value.map((item) => {
        bolwsData.value.push({
          foodName: item.name,
          foodId: item.id,
          price: item.price,
        });
      });
      wwcDialogVisible.value = false;
      // }
    }
    //自选套餐对话框显示与隐藏
    const chooseDialogVisible = ref(false);
    //自选套餐数据
    const chooseForm = ref([]);
    //自选套餐复选框数据
    const checkedChooseBoxs = ref([]);
    //添加自选称菜
    const editFormRef = ref(null);
    function addChooseFood() {
      chooseForm.value = [];
      if (canteenId.value) {
        checkedChooseBoxs.value = null;
        getCanteenFoodList(canteenId.value).then((res) => {
          checkedChooseBoxs.value = res.data.content;
          for (const i of checkedChooseBoxs.value) {
            optionalFoods.value.map((item) => {
              if (item.foodId === i.id) {
                i.checked = true;
              }
            });
          }
        });
        chooseDialogVisible.value = true;
      } else {
        ElMessage({
          message: "请选择食堂后，再操作",
          type: "warning",
        });
      }
    }
    //重装自选套餐数组
    const optionalFoods = ref([]);
    //提交自选套餐
    function submitChooseFood() {
      optionalFoods.value = [];
      chooseForm.value.map((item) => {
        optionalFoods.value.push({
          foodId: item.id,
          foodName: item.name,
          foodType: item.type,
          type: 2,
        });
        let setOptionFood = new Set(optionalFoods.value);
        optionalFoods.value = Array.from(setOptionFood);
      });
      chooseDialogVisible.value = false;
    }
    //提交表单
    function submitFood() {
      const foods = optionalFoods.value.concat(basicFoods.value);
      if (!foodId.value) {
        addFoodMenu({
          canteenId: canteenId.value,
          description: editForm.description,
          businessTime: editForm.businessTime,
          images: editForm.images,
          bowls: bolwsData.value,
          foods: foods,
        }).then(() => {
          ElMessage({
            message: "新增菜谱成功",
            type: "success",
          });
          router.back(-1);
        });
      } else {
        updateFoodMenu(foodId.value, {
          basicFoods: basicFoods.value,
          bowls: bolwsData.value,
          businessTime: editForm.businessTime,
          canteenId: canteenId.value,
          description: editForm.description,
          id: foodId.value,
          images: editForm.images,
          optionalFoods: optionalFoods.value,
        }).then(() => {
          ElMessage.success("更新成功");
          router.back(-1);
        });
      }
    }
    //菜谱ID
    const foodId = ref("");
    const route = useRoute();
    //通过ID获取菜谱信息
    function getFoodMenuData() {
      if (foodId.value) {
        getFoodMenuList(foodId.value).then((res) => {
          fileList.value.push({ url: res.data.images });
          (editForm.description = res.data.description),
            (editForm.businessTime = res.data.businessTime);
          bolwsData.value = res.data.bowls;
          basicFoods.value = res.data.basicFoods;
          editForm.images = res.data.images;
          optionalFoods.value = res.data.optionalFoods;
          editForm.region = res.data.canteen.id;
          canteenId.value = res.data.canteen.id;
        });
      }
    }
    function cancelBolws() {
      bowls.value = [];
      wwcDialogVisible.value = false;
    }
    const wwcMap = new Map();
    function chengeRadio(object, id) {
      wwcMap.set(id, object);
    }
    //移除菜品事件
    function removeFood(val) {
      bowls.value.forEach((item, index) => {
        if (item.id === val) {
          bowls.value.splice(index, 1);
          wwcForm.value[foodMap.get(item.id)] = null;
          wwcMap.delete(item.id);
        }
      });
    }
    onMounted(() => {
      foodId.value = route.query.id;
      getCanteen();
      getFoodMenuData();
      getWwcPrice();
    });
    const editFormRules = ref({});
    const searchForm = ref({});
    //菜品搜索
    function searchFood() {
      queryFood(canteenId.value, {
        name: searchForm.value.name ? searchForm.value.name : "",
      }).then((res) => {
        wwcForm.value = [];
        checkedBasicBoxs.value = res.data;
        wwcFoodData.value = res.data;
        checkedChooseBoxs.value = res.data;
      });
    }
    function reset() {
      searchForm.value.name = "";
      getCanteenFoodList(canteenId.value).then((res) => {
        checkedBasicBoxs.value = res.data.content;
        wwcFoodData.value = res.data;
        checkedChooseBoxs.value = res.data;
        //数组增加checked属性，控制选中和未选中
      });
    }
    //获取碗碗菜价格
    function getWwcPrice() {
      getBlowsPrice().then((res) => {
        wwcprice.value = res.data;
      });
    }
    function submitAudit() {
      console.log(foodId.value);
      menuAudit([foodId.value])
        .then(() => {
          ElMessage.success("提交成功");
          router.back(-1);
        })
        .catch((err) => {
          console.log(err);
        });
    }
    return {
      submitAudit,
      reset,
      searchForm,
      searchFood,
      foodId,
      editFormRules,
      editForm,
      header,
      canteenData,
      handlePictureCardPreview,
      handleRemove,
      handleSuccess,
      fileList,
      imgDialogVisible,
      dialogImageUrl,
      dialogVisible,
      addBasicFood,
      selectCanteen,
      basicForm,
      checkedBasicBoxs,
      checkedTags,
      submitBasicFood,
      wwcDialogVisible,
      addWwc,
      wwcForm,
      wwcFoodData,
      wwcprice,
      wwcTags,
      addWwcFood,
      addChooseFood,
      chooseDialogVisible,
      chooseForm,
      checkedChooseBoxs,
      submitChooseFood,
      submitWwcFood,
      submitFood,
      basicFoods,
      bowls,
      optionalFoods,
      cancel,
      chengeRadio,
      editFormRef,
      cancelBolws,
      bolwsData,
      removeFood,
      handleOnExceed,
      checkFileType,
    };
  },
};
</script>

<style scoped lang="scss">
.header {
  padding-bottom: 20px;
  margin-bottom: 20px;
  border-bottom: 1px solid #edeff3;
}

.dialog-header {
  display: flex;
  align-items: center;
}

.dialog-content {
  margin-top: 10px;
  height: 200px;
  border-radius: 6px;
  overflow-y: auto;
  border: 1px solid #d5d9de;
}

.tags {
  margin: 10px;
}

.item {
  display: flex;
  justify-content: space-between;
  overflow-y: auto;

  .item-left {
    margin-right: 20px;
  }
}
</style>
